import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ShopVo.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';

import '../../../EcyRouter.dart';
import '../../../constant/constant.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../../model/SysFile.dart';
import '../../goods/model/EcyGoodsHomeCategoryListModel.dart';
import '../../goods/model/EcyGoodsHomeCategoryModel.dart';
import '../../goods/model/EcyGoodsHomeIPListModel.dart';
import '../../goods/model/EcyGoodsHomeIPModel.dart';
import '../../goods/widgets/common/Debouncer.dart';
import '../model/ConsignProduct.dart';
import '../model/ConsignProductImages.dart';
import 'package:flutter/cupertino.dart';

class EcyConsignmentPublishPage extends StatefulWidget {
  int? productId;

  EcyConsignmentPublishPage(this.productId, {required super.key});

  @override
  State<EcyConsignmentPublishPage> createState() =>
      _EcyConsignmentPublishPageState(this.productId);
}

class _EcyConsignmentPublishPageState extends State<EcyConsignmentPublishPage> {
  int? productId;
  _EcyConsignmentPublishPageState(this.productId);

  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _subTitleController = TextEditingController();

  final ImagePicker _picker = ImagePicker();
  final List<ConsignProductImages> _imageList = [];
  List<XFile> _xFileList = [];
  final int _maxFileCount = 6;

  String _categoryCode = "";
  String _ipCode = "";
  int? _finenessIndex;
  int? _originalPackageIndex;

  final _priceController = TextEditingController();
  final _addressController = TextEditingController();
  double _price = 0.0;
  String? _shopId;
  String? _shopName;

  final List<EcyGoodsHomeCategoryModel> _categoryList = [];
  final List<EcyGoodsHomeIPModel> _ipList = [];
  final List<EcyGoodsHomeIPModel> _allIpList = [];
  List<ShopVo> _shopVoList = [];
  final List<String> _finenessList = ["全新", "几乎全新", "轻微使用痕迹", "明显使用"];
  final List<String> _originalPackageList = ["  是  ", "  否  "];
  final TextEditingController _searchController = TextEditingController();
  final Debounce debounce = Debounce();

  bool _loading = false;
  bool _publishFlag = false;
  ConsignProduct _consignProduct = ConsignProduct();
  final ScrollController _scrollController = ScrollController();
  int _ipTotal = 0;
  int _ipPage = 1;


  @override
  void initState() {
    super.initState();

    _loading = false;

    requestIpAndCategoryData();

    if (productId != null) {
      loadDetail(productId!);
    }

    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _titleController.dispose();
    _subTitleController.dispose();
    _priceController.dispose();
    _addressController.dispose();
    _scrollController.dispose();
    _searchController.dispose();
  }


  void _onScroll() {
    if (_ipPage < _ipTotal) {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        requestIpData();
      }
    }
  }

  //查询品牌数据
  Future<bool> requestIpData() async {
    Map<String, dynamic> response = {};
    try {
      response = await EcyRequestbasemanager().post("/app/api/app/commodityIp/list",
          {"size": "50", "current": _ipPage, "name": _searchController.text});
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
    if (response.isNotEmpty) {
      reloadIPDrawer(response);
    }
    return true;
  }

  //查询品牌、分类数据
  Future<bool> requestIpAndCategoryData() async {
    List<Map<String, dynamic>> response = [];
    try {
      response = await Future.wait([
        EcyRequestbasemanager().post("/app/api/app/commodityIp/list",
            {"size": "50", "current": _ipPage, "name": ""}),
        EcyRequestbasemanager().post("/app/api/app/commodityCategory/list",
            {"size": "50", "current": "1", "name": ""}),
        EcyRequestbasemanager()
            .post("/app/api/app/consign/depository/list", {}),
      ]);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
    if (response.isNotEmpty) {
      var ipResp = response[0];
      if (ipResp != null) {
        reloadIPArea(ipResp);
      }
      var categoryResp = response[1];
      if (categoryResp != null) {
        reloadCategoryArea(categoryResp);
      }
      var shopResp = response[2];
      if (shopResp != null) {
        reloadShopResp(shopResp);
      }
    }
    return true;
  }

  Future<void> loadDetail(int productId) async {
    Map<String, dynamic> body = {
      "productId": productId,
    };
    var response =
        await EcyRequestbasemanager().post("/app/api/app/consign/detail", body);
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _consignProduct = ConsignProduct.fromJson(response["data"]);
          _titleController.text = _consignProduct.title ?? "";
          _subTitleController.text = _consignProduct.description ?? "";
          _publishFlag = _consignProduct.status ==
              "1"; // 商品状态：-1:锁定（下单）0:草稿、1:上架、2:已售出、3:已下架，默认为草稿
          _categoryCode = _consignProduct.categoryCode ?? "";
          _ipCode = _consignProduct.brandCode ?? "";
          _finenessIndex = _consignProduct.condition == "0" ? 0 : 1;
          _originalPackageIndex =
              _consignProduct.hasOriginalPackaging ?? false ? 1 : 0;
          _price = _consignProduct.price ?? 0.0;
          _shopId = _consignProduct.shopId;
          _shopName = _consignProduct.shop?.name;
          _imageList.addAll(_consignProduct.images ?? []);
        });
      }
    }
  }

  void reloadIPArea(ipResp) {
    try {
      var ipRespModel = EcyApiCommonResponse.fromJson(ipResp, (ipResp) => json);
      if (ipRespModel.code == 0 || ipRespModel.code == 200) {
        EcyGoodsHomeIPListModel ipListModel =
            EcyGoodsHomeIPListModel.fromJson(ipResp["data"]);
        setState(() {
          if (ipListModel.records.length > 3) {
            _ipList.addAll(ipListModel.records.sublist(0, 3));
          } else {
            _ipList.addAll(ipListModel.records);
          }
          _ipTotal = ipListModel.pages;
          _ipPage = ipListModel.current;
          _allIpList.addAll(ipListModel.records);
          _ipList.add(EcyGoodsHomeIPModel(
              "更多", "-1", "更多", "-1", "", false, false, "-1"));

          _ipPage ++ ;
        });
      }
    } catch (e) {
      EcyLogger.log("获取品牌失败");
    }
  }

  void reloadIPDrawer(ipResp) {
    try {
      var ipRespModel = EcyApiCommonResponse.fromJson(ipResp, (ipResp) => json);
      if (ipRespModel.code == 0 || ipRespModel.code == 200) {
        EcyGoodsHomeIPListModel ipListModel =
          EcyGoodsHomeIPListModel.fromJson(ipResp["data"]);
        if(ipListModel.current == 1) {
          _allIpList.clear();
        }
        setState(() {
          _ipTotal = ipListModel.pages;
          _ipPage = ipListModel.current;
          _allIpList.addAll(ipListModel.records);
          _ipPage ++ ;
        });
      }
    } catch (e) {
      EcyLogger.log("获取品牌失败");
    }
  }

  void reloadCategoryArea(categoryResp) {
    var commonResponse =
        EcyApiCommonResponse.fromJson(categoryResp, (categoryResp) => json);
    if (commonResponse.code == 0 || commonResponse.code == 200) {
      EcyGoodsHomeCategoryListModel categoryRespModel =
          EcyGoodsHomeCategoryListModel.fromJson(categoryResp["data"]);
      setState(() {
        _categoryList.addAll(categoryRespModel.records);
      });
    }
  }

  void reloadShopResp(response) {
    try {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (ipResp) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        List<ShopVo> shopVoList = ((response["data"] ?? []) as List<dynamic>)
            .map((e) => ShopVo.fromJson(e as Map<String, dynamic>))
            .toList();
        _shopVoList = shopVoList;
      }
    } catch (e) {
      EcyLogger.log("获取品牌失败");
    }
  }

  Future<void> _pickMultiImage() async {
    final List<XFile> pickedFiles = await _picker.pickMultiImage(
        limit: _maxFileCount, imageQuality: 100); // 从相册选择图片
    if (pickedFiles != null && pickedFiles.isNotEmpty) {
      _xFileList.addAll(pickedFiles);
      var sublist =
          _xFileList.length > 6 ? _xFileList.sublist(0, 6) : _xFileList;
      setState(() {
        _xFileList = sublist;
      });
    }
  }

  void _removeImage(int index, {int removeType = 0}) {
    if (removeType == 0) {
      setState(() {
        _imageList.removeAt(index);
      });
    } else {
      setState(() {
        _xFileList.removeAt(index);
      });
    }
  }

  bool _validate() {
    if (_titleController.text == null || _titleController.text.trim().isEmpty) {
      EasyLoading.showToast("请添加标题", duration: const Duration(seconds: 1));
      return false;
    }
    if (_subTitleController.text == null ||
        _subTitleController.text.trim().isEmpty) {
      EasyLoading.showToast("请添加描述", duration: const Duration(seconds: 1));
      return false;
    }
    if (_imageList.isEmpty && _xFileList.isEmpty) {
      EasyLoading.showToast("请上传图片", duration: const Duration(seconds: 1));
      return false;
    }
    if (_categoryCode.isEmpty) {
      EasyLoading.showToast("请选择分类", duration: const Duration(seconds: 1));
      return false;
    }
    if (_finenessIndex == null) {
      EasyLoading.showToast("请选择成色", duration: const Duration(seconds: 1));
      return false;
    }
    if (_originalPackageIndex == null) {
      EasyLoading.showToast("请选择是否有原包装", duration: const Duration(seconds: 1));
      return false;
    }
    if (_price <= 0.0) {
      EasyLoading.showToast("请输入价格", duration: const Duration(seconds: 1));
      return false;
    }
    if (_shopId == null) {
      EasyLoading.showToast("请选择寄存点", duration: const Duration(seconds: 1));
      return false;
    }
    return true;
  }

  /// 0|草稿 1|发布
  Future<void> saveConsignment({String status = "0"}) async {
    if (_loading) {
      return;
    }
    setState(() {
      _loading = true;
    });

    var okFlag = _validate();
    if (!okFlag) {
      setState(() {
        _loading = false;
      });
      return;
    }

    EasyLoading.show(status: '处理中...');
    try {
      if (_xFileList.isNotEmpty) {
        List<MultipartFile> multipartFileList = [];
        for (var xFile in _xFileList) {
          multipartFileList.add(
              MultipartFile.fromFileSync(xFile.path, filename: xFile.name));
        }

        var formData = FormData.fromMap({
          "files": multipartFileList,
        });
        var fileResponse =
            await EcyRequestbasemanager().post("/file/uploads", formData);
        if (fileResponse != null) {
          var commonResponse = EcyApiCommonResponse.fromJson(
              fileResponse, (fileResponse) => json);
          if (commonResponse.code == 0 || commonResponse.code == 200) {
            for (var e in ((fileResponse["data"] ?? []) as List<dynamic>)) {
              SysFile sysFile = SysFile.fromJson(e as Map<String, dynamic>);
              ConsignProductImages newImage = ConsignProductImages();
              newImage.imageUrl = sysFile.name;
              _imageList.add(newImage);
            }
          }
        }
      }

      for (var currImage in _imageList) {
        currImage.imageUrl = currImage.imageUrl
            ?.replaceFirst(Constant.OSS_FILE_PATE_PREFIX, "")
            .replaceFirst(Constant.FILE_PATE_PREFIX, "");
      }

      _consignProduct.title = _titleController.text;
      _consignProduct.description = _subTitleController.text;
      _consignProduct.categoryCode = _categoryCode;
      _consignProduct.brandCode = _ipCode;
      _consignProduct.condition = _finenessIndex.toString();
      _consignProduct.hasOriginalPackaging = _originalPackageIndex == 0;
      _consignProduct.price = _price;
      _consignProduct.status = status;
      _consignProduct.shopId = _shopId;
      _consignProduct.images = _imageList;

      String currUrl = status == "0" ? "/draft" : "/publish";
      var response = await EcyRequestbasemanager()
          .post("/app/api/app/consign$currUrl", _consignProduct);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast(
              (status == "0" || _publishFlag) ? "保存成功" : "发布成功",
              duration: const Duration(seconds: 1));
        } else {
          EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
          return;
        }
      }

      if (status == "0") {
        if (_consignProduct.productId == null) {
          EcyRouter().pushReplacement(
              context, EcyRouter.myConsignmentPublishListPage, true);
        } else {
          Navigator.pop(context, true);
        }
      } else {
        Navigator.pop(context, true);
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
    } finally {
      EasyLoading.dismiss();
      _loading = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> widgetList = [
      Expanded(
        flex: 5,
        child: Container(
          height: 40.0,
          padding: const EdgeInsets.only(left: 10),
          child: TextButton(
              onPressed: () {
                saveConsignment(status: "1");
              },
              style: const ButtonStyle(
                alignment: Alignment.center,
                backgroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                foregroundColor: WidgetStatePropertyAll(Colors.white),
              ),
              child: Text(
                _publishFlag ? '保存' : '发布',
                style: const TextStyle(
                  height: 1,
                  fontSize: 18,
                  leadingDistribution:
                      TextLeadingDistribution.even, // 设置leading策略
                ),
              )),
        ),
      )
    ];
    if (!_publishFlag) {
      widgetList.insert(
          0,
          Expanded(
              flex: 1,
              child: GestureDetector(
                onTap: saveConsignment,
                child: Column(
                  children: [
                    const Padding(padding: EdgeInsets.only(bottom: 4)),
                    const Image(
                        image: AssetImage('assets/images/ic_drafts.png'),
                        width: 32),
                    Text(
                      _consignProduct.productId != null ? "保存" : "存草稿",
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF8C8C8C),
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              )));
    }

    return Scaffold(
      backgroundColor: const Color(0XFFF5F5F5),
      appBar: AppBar(
          backgroundColor: Colors.white,
          scrolledUnderElevation: 0,
          centerTitle: true,
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
          title: Text(
            "发布闲置",
            style: TextStyle(
                fontFamily: "PingFang SC",
                fontSize: 16.sp,
                color: const Color(0xD9000000),
                fontWeight: FontWeight.w600),
          )
      ),
      endDrawer: Drawer(
        child: Column(
          children: [
            const Padding(padding: EdgeInsets.only(bottom: 40)),
            Text(
              '选择品牌',
              style: TextStyle(
                  fontFamily: "PingFang SC",
                  fontWeight: FontWeight.w700,
                  fontSize: 16.sp,
                  color: const Color(0xFF262626)),
            ),
            Container(
              margin: EdgeInsets.only(left: 4.w),
              height: 36.h,
              width: MediaQuery.of(context).size.width - 100.w,
              child: TextField(
                controller: _searchController,
                textAlignVertical: TextAlignVertical.center,
                decoration: InputDecoration(
                  hintText: "搜索",
                  hintStyle: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w300,
                      color: const Color(0x73000000)),
                  prefixIcon: const Icon(
                    Icons.search,
                    color: Color(0x73000000),
                  ),
                  // 设置前置图标的约束
                  prefixIconConstraints: BoxConstraints(
                    //添加内部图标之后，图标和文字会有间距，实现这个方法，不用写任何参数即可解决
                      minWidth: 30.w
                  ),
                  contentPadding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                  isDense: true,
                  border: UnderlineInputBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    borderSide: const BorderSide(
                      color: Color(0x73000000), // 修改下划线颜色
                      width: 1, // 修改下划线宽度
                    ),
                  ), // 移除默认边框
                  focusedBorder: const UnderlineInputBorder(
                    // 获取焦点时的下划线
                    borderSide: BorderSide(
                      color: Color(0x73000000), // 修改下划线颜色
                      width: 1, // 修改下划线宽度
                    ),
                  ),
                  enabledBorder: const UnderlineInputBorder(
                    // 默认状态下的下划线
                    borderSide: BorderSide(
                      color: Color(0x73000000), // 修改下划线颜色
                      width: 1, // 修改下划线宽度
                    ),
                  ),
                ),
                onChanged: (String value) {
                  debounce.setDuration(const Duration(milliseconds: 300), () {
                    _ipPage = 1;
                    requestIpData();
                  });
                },
              ),
            ),
            Expanded(child: _getGridView(_allIpList)),
            const Padding(padding: EdgeInsets.only(top: 10)),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            //触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 18),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 8),
                    child: TextFormField(
                      controller: _titleController,
                      decoration: InputDecoration(
                        hintText: '标题',
                        hintFadeDuration: Duration.zero,
                        border: InputBorder.none,
                        counterText: '',
                        hintStyle: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFFBFBFBF)),
                      ),
                      maxLength: 20,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8),
                    child: TextFormField(
                      controller: _subTitleController,
                      decoration: InputDecoration(
                        hintText: '添加描述，能帮助您更快卖出哦~',
                        hintFadeDuration: Duration.zero,
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14.sp,
                            color: const Color(0xFFBFBFBF)),
                        counterText: '',
                      ),
                      minLines: 3,
                      maxLines: 8,
                      maxLength: 500,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8, top: 8, right: 8),
                    child: SizedBox(
                      height: 80.w,
                      child: _loadImages(),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 8, top: 30, bottom: 8),
                    child: Text(
                      "选择",
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w700,
                          fontSize: 16.sp,
                          color: const Color(0xFF262626)),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          alignment: Alignment.centerRight,
                          width: 50.w,
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          child: const Text(
                            '分类',
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xD9000000),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          height: 34,
                          width: MediaQuery.of(context).size.width - 90.w,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 3),
                            child: ListView.builder(
                              shrinkWrap: true,
                              physics: const AlwaysScrollableScrollPhysics(),
                              scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                              itemCount: _categoryList.length,
                              itemBuilder: (context, index) {
                                var currCategory = _categoryList[index];
                                return GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      _categoryCode = currCategory.code ?? "";
                                    });
                                  },
                                  child: Card(
                                    color: _categoryCode == currCategory.code
                                        ? const Color(0xFFEA4B9B)
                                        : const Color(0xFFf5f5f5),
                                    shape: const RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(5)),
                                    ),
                                    child: Container(
                                      height: 20,
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 8),
                                      child: Align(
                                        alignment: Alignment.center,
                                        child: Text(
                                          currCategory.name ?? "",
                                          style: TextStyle(
                                              color: _categoryCode ==
                                                      currCategory.code
                                                  ? Colors.white
                                                  : Colors.black),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          alignment: Alignment.centerRight,
                          width: 50.w,
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          child: const Text(
                            '品牌',
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xD9000000),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          height: 34,
                          width: MediaQuery.of(context).size.width - 90.w,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 3),
                            child: ListView.builder(
                              shrinkWrap: true,
                              physics: const AlwaysScrollableScrollPhysics(),
                              scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                              itemCount: _ipList.length,
                              itemBuilder: (context, index) {
                                var currIp = _ipList[index];
                                return GestureDetector(
                                    onTap: () {
                                      if (currIp.code == "-1") {
                                        _searchController.text = "";
                                        Scaffold.of(context).openEndDrawer();
                                      } else {
                                        setState(() {
                                          _ipCode = currIp.code ?? "";
                                        });
                                      }
                                    },
                                    child: Card(
                                      color: _ipCode == currIp.code
                                          ? const Color(0xFFEA4B9B)
                                          : const Color(0xFFf5f5f5),
                                      shape: const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(5)),
                                      ),
                                      child: Container(
                                        height: 20,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: Text(
                                            currIp.name ?? "",
                                            style: TextStyle(
                                                color: _ipCode == currIp.code
                                                    ? Colors.white
                                                    : Colors.black),
                                          ),
                                        ),
                                      ),
                                    ));
                              },
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          width: 50.w,
                          alignment: Alignment.centerRight,
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          child: const Text(
                            '成色',
                            softWrap: true,
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xD9000000),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          height: 34,
                          width: MediaQuery.of(context).size.width - 90.w,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 3),
                            child: ListView.builder(
                              shrinkWrap: true,
                              physics: const AlwaysScrollableScrollPhysics(),
                              scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                              itemCount: _finenessList.length,
                              itemBuilder: (context, index) {
                                var currFineness = _finenessList[index];
                                return GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        _finenessIndex = index;
                                      });
                                    },
                                    child: Card(
                                      color: _finenessIndex == index
                                          ? const Color(0xFFEA4B9B)
                                          : const Color(0xFFf5f5f5),
                                      shape: const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(5)),
                                      ),
                                      child: Container(
                                        height: 20,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: Text(
                                            currFineness,
                                            style: TextStyle(
                                                color: _finenessIndex == index
                                                    ? Colors.white
                                                    : Colors.black),
                                          ),
                                        ),
                                      ),
                                    ));
                              },
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          width: 50.w,
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          child: const Align(
                            alignment: Alignment.centerRight,
                            child: Text(
                              '是否有原包装',
                              softWrap: true,
                              style: TextStyle(
                                fontSize: 14,
                                color: Color(0xD9000000),
                              ),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.zero,
                          margin: EdgeInsets.zero,
                          height: 34,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 3),
                            child: ListView.builder(
                              shrinkWrap: true,
                              physics: const AlwaysScrollableScrollPhysics(),
                              scrollDirection: Axis.horizontal, // 设置滚动方向为水平
                              itemCount: _originalPackageList.length,
                              itemBuilder: (context, index) {
                                var currOriginalPackage =
                                    _originalPackageList[index];
                                return GestureDetector(
                                    onTap: () {
                                      setState(() {
                                        _originalPackageIndex = index;
                                      });
                                    },
                                    child: Card(
                                      color: _originalPackageIndex == index
                                          ? const Color(0xFFEA4B9B)
                                          : const Color(0xFFf5f5f5),
                                      shape: const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(5)),
                                      ),
                                      child: Container(
                                        height: 20,
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        child: Align(
                                          alignment: Alignment.center,
                                          child: Text(
                                            currOriginalPackage,
                                            style: TextStyle(
                                                color: _originalPackageIndex ==
                                                        index
                                                    ? Colors.white
                                                    : Colors.black),
                                          ),
                                        ),
                                      ),
                                    ));
                              },
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Card(
                    color: Colors.white,
                    margin: const EdgeInsets.all(0),
                    shadowColor: Colors.transparent,
                    shape: const RoundedRectangleBorder(
                        side: BorderSide(color: Colors.black12, width: 1),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: ListTile(
                      contentPadding: EdgeInsets.symmetric(horizontal: 8),
                      title: const Text(
                        '价格',
                        style: TextStyle(
                            color: Color(0xD9000000),
                            fontSize: 16,
                            fontWeight: FontWeight.w600),
                      ),
                      trailing: RichText(
                        text: TextSpan(children: [
                          TextSpan(
                              text: '￥$_price',
                              style: const TextStyle(
                                  color: Colors.red, fontSize: 18)),
                          const WidgetSpan(
                              alignment: PlaceholderAlignment.top,
                              child: Icon(Icons.arrow_forward_ios, size: 14)),
                        ]),
                      ),
                      splashColor: Colors.transparent,
                      onTap: () {
                        _showModalBottomSheet(context);
                      },
                    ),
                  ),
                  const Padding(padding: EdgeInsets.only(bottom: 10)),
                  Card(
                    color: Colors.white,
                    margin: const EdgeInsets.all(0),
                    shadowColor: Colors.transparent,
                    shape: const RoundedRectangleBorder(
                        side: BorderSide(color: Colors.black12, width: 1),
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: ListTile(
                      contentPadding: const EdgeInsets.symmetric(horizontal: 8),
                      title: const Text(
                        '寄存点',
                        style: TextStyle(
                            color: Color(0xD9000000),
                            fontSize: 14,
                            fontWeight: FontWeight.w600),
                      ),
                      trailing: RichText(
                        text: TextSpan(children: [
                          TextSpan(
                              text: _shopName ?? "",
                              style: const TextStyle(
                                  color: Colors.grey, fontSize: 18)),
                          const WidgetSpan(
                              alignment: PlaceholderAlignment.top,
                              child: Icon(Icons.arrow_forward_ios, size: 14)),
                        ]),
                      ),
                      splashColor: Colors.transparent,
                      onTap: () {
                        _showAddressBottomSheet(context);
                      },
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: widgetList,
        ),
      ),
    );
  }

  Widget _loadImages() {
    Widget avatar = Image.asset('assets/images/login_app_icon.png',
        width: 80, height: 80, fit: BoxFit.fitHeight);
    int imageLength = _imageList.length;
    int xFileLength = _xFileList.length;
    int sum = imageLength + xFileLength;
    return ListView.builder(
      shrinkWrap: true,
      physics: const AlwaysScrollableScrollPhysics(),
      scrollDirection: Axis.horizontal, // 设置滚动方向为水平
      itemCount: sum + 1,
      itemBuilder: (context, index) {
        if (_imageList.isNotEmpty && index < imageLength) {
          var currImage = _imageList[index];
          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: Stack(
              children: [
                CachedNetworkImage(
                  width: 80.w,
                  height: 80.w,
                  imageUrl: currImage.imageUrl ?? "",
                  imageBuilder: (context, imageProvider) => Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.r)),
                        image: DecorationImage(
                            image: imageProvider, fit: BoxFit.cover)),
                  ),
                  placeholder: (context, url) => avatar,
                  errorWidget: (context, url, error) => avatar,
                ),
                Positioned(
                  top: 0.0,
                  right: 0.0,
                  width: 20,
                  height: 20,
                  child: GestureDetector(
                    child: SizedBox(
                      child: Image.asset('assets/images/ic_delete_1.png'),
                    ),
                    onTap: () => _removeImage(index),
                  ),
                ),
              ],
            ),
          );
        }
        if (_xFileList.isNotEmpty && imageLength - 1 < index && index < sum) {
          var xFile = _xFileList[index - imageLength];
          return Padding(
              padding: const EdgeInsets.only(right: 8),
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: SizedBox(
                        width: 80.w,
                        height: 80.w,
                        child: Image.file(
                          File(xFile.path),
                          width: 80.w,
                          height: 80.w,
                          fit: BoxFit.cover,
                        )),
                  ),
                  Positioned(
                    top: 0.0,
                    right: 0.0,
                    width: 20.w,
                    height: 20.w,
                    child: GestureDetector(
                      child: SizedBox(
                        child: Image.asset('assets/images/ic_delete_1.png'),
                      ),
                      onTap: () =>
                          _removeImage(index - imageLength, removeType: 1),
                    ),
                  ),
                ],
              ));
        }
        if (sum < 6) {
          return SizedBox(
            height: 80.w,
            width: 80.w,
            child: GestureDetector(
              onTap: () {
                _pickMultiImage();
              },
              child: Image(
                image: const AssetImage('assets/images/ic_add.png'),
                width: 80.w,
                height: 80.w,
              ),
            ),
          );
        }
      },
    );
  }

  // 价格
  void _showModalBottomSheet(BuildContext context) async {
    _priceController.text = _price.toString();
    var result = await showModalBottomSheet(
      isScrollControlled: true,
      isDismissible: true, //点击空白处返回功能，默认是true
      enableDrag: true, //是否允许拖动
      elevation: 10,
      backgroundColor: Colors.white, //背景颜色
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ), //圆角
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setState) {
        final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
        return Padding(
            padding: EdgeInsets.only(bottom: keyboardHeight), //设置底部内边距为软件盘高度
            child: Container(
              height: 150.w,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30.w),
                  topRight: Radius.circular(30.w),
                ),
                color: Colors.white,
              ),
              child: Column(
                children: <Widget>[
                  // 标题
                  Center(
                    child: Text(
                      "请输入价格",
                      style: TextStyle(
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                  TextField(
                    autofocus: true,
                    controller: _priceController,
                    textAlign: TextAlign.center,
                    //只允许输入小数
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                      TextInputFormatter.withFunction((oldValue, newValue) {
                        // 确保只有一个小数点，并处理多位小数点的情况
                        if (newValue.text.contains(".") &&
                            (newValue.text.split(".").length > 2 ||
                                newValue.text.split(".")[1].length > 2)) {
                          return oldValue; // 返回旧值，不更新文本框内容
                        }
                        return newValue; // 返回新值，允许更新文本框内容
                      }),
                    ],
                    //键盘类型
                    keyboardType:
                        const TextInputType.numberWithOptions(decimal: true),
                    decoration: const InputDecoration(
                      counterText: '',
                    ),
                    maxLength: 20,
                  ),
                  SizedBox(
                    width: 200.w,
                    height: 50.w,
                    child: Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: TextButton(
                            onPressed: () {
                              //触摸收起键盘
                              FocusScope.of(context).requestFocus(FocusNode());
                              Navigator.pop(context, true);
                            },
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                              backgroundColor:
                                  WidgetStatePropertyAll(Color(0xFFEA4B9B)),
                              foregroundColor:
                                  WidgetStatePropertyAll(Colors.white),
                            ),
                            child: const Text(
                              '确定价格',
                              style: TextStyle(
                                height: 1,
                                fontSize: 18,
                                leadingDistribution:
                                    TextLeadingDistribution.even, // 设置leading策略
                              ),
                            ))),
                  )
                ],
              ),
            ));
      }),
    );

    if (result) {
      setState(() {
        _price = double.parse(_priceController.text);
      });
    }
  }

  GridView _getGridView(List<EcyGoodsHomeIPModel> ipList) {
    return GridView.builder(
      controller: _scrollController,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4, //每行三列
        childAspectRatio: 1.0, //显示区域宽高相等
      ),
      itemCount: ipList.length,
      itemBuilder: (context, index) {
        EcyGoodsHomeIPModel item = ipList[index];
        return GestureDetector(
          onTap: () {
            setState(() {
              _ipCode = item.code ?? "";
              _ipList.removeWhere((n) => n.id == item.id);
              _ipList.insert(0, item);
            });
            Scaffold.of(context).closeEndDrawer();
          },
         child: itemContainer(index, item),
        );
      },
    );
  }

  Widget itemContainer(int index, EcyGoodsHomeIPModel item) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(top: 8.h),
          child: CachedNetworkImage(
            width: 44.w,
            height: 44.w,
            imageUrl: (item.iconUrl ?? ""),
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(8.r)),
                  image: DecorationImage(
                      image: imageProvider, fit: BoxFit.contain)),
            ),
            // placeholder: (context, url) =>
            //     CircularProgressIndicator(),
            errorWidget: (context, url, error) => const Icon(Icons.error),
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          item.name ?? item.remark ?? "",
          style: TextStyle(
              fontWeight: FontWeight.w300,
              fontSize: 12.sp,
              overflow: TextOverflow.ellipsis,
              color: const Color(0xD9000000)),
        ),
      ],
    );
  }

  // 寄存点
  void _showAddressBottomSheet(BuildContext context) async {
    await showModalBottomSheet(
      isDismissible: true, //点击空白处返回功能，默认是true
      enableDrag: true, //是否允许拖动
      elevation: 10,
      backgroundColor: Colors.white, //背景颜色
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
        topLeft: Radius.circular(10),
        topRight: Radius.circular(10),
      )), //圆角
      context: context,
      builder: (context) => StatefulBuilder(builder: (context, setState) {
        List<Widget> widgetList = _shopVoList.map((e) {
          return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () => {
                    setState(() {
                      _shopId = e.id;
                      _shopName = e.name;
                    }),
                  },
              child: Padding(padding: const EdgeInsets.only(top: 10), child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(e.name ?? "***",
                      style:
                      const TextStyle(color: Colors.black, fontSize: 16)),
                  // 使用 RadioListTile 作为 Radio 的容器
                  Image(
                      image: AssetImage(_shopId == e.id
                          ? 'assets/images/login_checked.png'
                          : 'assets/images/login_unchecked.png'),
                      width: 24,
                      height: 24),
                ],
              ),));
        }).toList();

        return Container(
          height: 800.h,
          padding: const EdgeInsets.only(left: 16, right: 16),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(30.w),
              topRight: Radius.circular(30.w),
            ),
            color: Colors.white,
          ),
          child: Column(
            children: <Widget>[
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child:Icon(CupertinoIcons.chevron_compact_down,size: 30.w,)
                  ),
              // 标题
              SizedBox(
                height: 65.h,
                child: Center(
                  child: Text(
                    "请选择寄存点",
                    style: TextStyle(
                      fontSize: 16.sp,
                    ),
                  ),
                ),
              ),
              ...widgetList,
            ],
          ),
        );
      }),
    );

    setState(() {
      _shopName = _shopVoList.firstWhere((n) => n.id == _shopId)?.name;
    });
  }
}
